package com.cmit.lee.myaop.invocation;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Method;
import java.util.List;

/**
 * <br/>
 *
 * @author liyuanchang
 * @version V1.0
 * @email liyuanchang@chinamobile.com
 * @date 2020-04-15 21:25
 */
public class ProxyMethodInvocation implements MethodInvocation {
    private Method method;
    private Object[] args;
    private Object target;
    private List<MethodInterceptor> interceptorList;
    int currentIndex = -1;

    public ProxyMethodInvocation(Method method, Object[] args, Object target, List<MethodInterceptor> interceptorList) {
        this.method = method;
        this.args = args;
        this.target = target;
        this.interceptorList = interceptorList;
    }

    @Override
    public Method getMethod() {
        return this.method;
    }

    @Override
    public Object[] getArguments() {
        return this.args;
    }

    @Override
    public Object proceed() throws Throwable {
        if (currentIndex == interceptorList.size() -1) {
            return method.invoke(target, args);
        }

        MethodInterceptor nextInteceptor = interceptorList.get(++currentIndex);
        return nextInteceptor.invoke(this);
    }

    @Override
    public Object getThis() {
        return this.target;
    }

    @Override
    public AccessibleObject getStaticPart() {
        return this.method;
    }
}
